package org.cc.cstc.querystrategy;

import org.cc.cstc.querystrategy.impl.ErrorQueryStrategy;
import org.cc.cstc.querystrategy.impl.SqlQueryStrategy;
import org.cc.cstc.querystrategy.impl.TextQueryStrategy;
import org.cc.cstc.utils.ClipBoardUtil;
import org.cc.cstc.utils.StringUtils;
import org.jsoup.internal.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class InsertEditorData {

    private final Map<String, QueryStrategy> strategyMap = new HashMap<String, QueryStrategy>(16);

    private final String insertSqlRegex = "INSERT\\s+INTO\\s+`?(\\w+)`?\\s*\\(([^)]+)\\)\\s*(?:VALUES|ON DUPLICATE KEY UPDATE)";

    private final Pattern insertSqlPattern = Pattern.compile(insertSqlRegex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

    public InsertEditorData() {
        strategyMap.put("inertSql",new SqlQueryStrategy());
        strategyMap.put("text",new TextQueryStrategy());
        strategyMap.put("error",new ErrorQueryStrategy());
    }

    public List<String> getPreInsertData(){
        String clipBoardContent = ClipBoardUtil.getClipBoardContent();
        String contentType = getContentType(clipBoardContent.trim());
        if(StringUtil.isBlank(contentType)){
            return new ArrayList<>();
        }
        QueryStrategy queryStrategy = strategyMap.get(contentType.trim());
        if(queryStrategy == null){
            return new ArrayList<>();
        }
        return queryStrategy.queryField(clipBoardContent);
    }

    /**
     * 获取剪切板内容的类型
     * @param str 内容
     * @return 类型
     */
    private String getContentType(String str){
        Matcher matcher = insertSqlPattern.matcher(str);
        if(matcher.find()){
            return "inertSql";
        }else if(StringUtils.isSnakeCase(str)){
            return "text";
        }
        return "error";
    }

}
